const config = require('config.js');
// 小程序开发api接口统一配置
// 如果你的域名是： https://www.baidu.com/cn 那么这里只要填写 cn
let subDomain = '' // 子域名,没有就等于''
const API_BASE_URL = config.server // 主域名


const request = (url, data = {}, method = 'post') => {
  let _url = API_BASE_URL + subDomain + url
  return new Promise((resolve, reject) => {
    let session_id = wx.getStorageSync('session_id');
    let header = {
      "content-type": 'application/x-www-form-urlencoded'
    }
    if (session_id) {
      header.cookie = `session_id=${session_id}`;
    } else {
      if (!data) {
        data = {};
      }
      data.login = config.login;
      data.password = config.password;
      data.db = config.db;
    }
    wx.request({
      url: _url,
      header: header,
      data: data,
      dataType: 'json',
      method: method,
      success(res) {
        if (res.statusCode == 200) {
          resolve(res.data)
        } else {
          reject(res.data);
        }
      },
      fail(error) {
        reject(error)
      }
    })
  })
}

const requsetImageUrl = (model, field, id) => {
  let session_id = wx.getStorageSync('session_id');
  return `${config.server}/web/image?` +
    `model=${model}&field=${field}&id=${id}&session_id=${session_id}`;
}

/**
 * 获取购物车
 */
const getCartCount = () => {
  let is_login = wx.getStorageSync('is_login');

  if (!is_login) {
    return;
  }
  let params = {
    user_id: wx.getStorageSync('is_login'),
  };
  request('/wechatshop/getCartCount', params).then(data => {

    let app = getApp();
    app.globalData.cartCount = data.count;
    wx.setTabBarBadge({
      index: 2,
      text: app.globalData.cartCount.toString(),
    })
  })
}

/**
 * 小程序的promise没有finally方法，自己扩展下
 */
Promise.prototype.finally = function(callback) {
  var Promise = this.constructor;
  return this.then(
    function(value) {
      Promise.resolve(callback()).then(
        function() {
          return value;
        }
      );
    },
    function(reason) {
      Promise.resolve(callback()).then(
        function() {
          throw reason;
        }
      );
    }
  );
}

module.exports = {
  request,
  requsetImageUrl,
  getCartCount
}